package com.aistar.task;

import com.aistar.pojo.Contest;
import com.aistar.service.ContestService;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.*;
import net.fortuna.ical4j.model.component.VAlarm;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.property.*;
import net.fortuna.ical4j.util.UidGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;

/*
生成日历文件
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class QuartZTask {
    private final ContestService contestService;
    private final String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/static/dist/ics/contest.ics";

    @Autowired
    public QuartZTask(ContestService contestService) {
        this.contestService = contestService;
    }

    //3.添加定时任务
    @Scheduled(cron = "1 00 12 ? * SUN")
//    @Scheduled(cron = "5/5 * * * * ?") // 每5s运行一次
    private void configureTasks() {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在");
            make();
        } else {
            file.delete();
            System.out.println("文件存在");
            make();
            System.out.println("创建文件");
        }
    }

    public void make() {
        Contest contest = (Contest) contestService.getRecentContest().getData();
        System.out.println(contest);
        try {
            // 创建一个时区（TimeZone）
            TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
            TimeZone timezone = registry.getTimeZone("Asia/Shanghai");
            VTimeZone tz = timezone.getVTimeZone();

            // 创建日历
            Calendar calendar = new Calendar();
            calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
            calendar.getProperties().add(Version.VERSION_2_0);
            calendar.getProperties().add(CalScale.GREGORIAN);

            // 时间主题
            String summary = "hello竞赛";
            // 开始时间
            DateTime start = new DateTime(contest.getContestStartTime().getTime());
            // 开始时间转换为UTC时间（UTC ＋ 时区差 ＝ 本地时间 ）
            start.setUtc(true);
            // 结束时间
            DateTime end = new DateTime(contest.getContestEndTime().getTime());
            // 结束时间设置成UTC时间（UTC ＋ 时区差 ＝ 本地时间 ）
            end.setUtc(true);
            // 新建普通事件
            // VEvent event = new VEvent(start, end, summary);
            // 定义全天事件（注意默认是UTC时间）
            VEvent event = new VEvent(new Date(contest.getContestStartTime().getTime()), new Date(contest.getContestEndTime().getTime()), summary);
            event.getProperties().add(new Location(contest.getContestName()));
            // 生成唯一标示
            event.getProperties().add(new Uid(new UidGenerator("iCal4j").generateUid().getValue()));
            // 添加时区信息
            event.getProperties().add(tz.getTimeZoneId());
            // 添加邀请者
            Attendee dev1 = new
                    Attendee(URI.create("mailto:dev1@mycompany.com"));
            dev1.getParameters().add(Role.REQ_PARTICIPANT);
            dev1.getParameters().add(new Cn("Developer 1"));
            event.getProperties().add(dev1);
            // 重复事件
            Recur recur = new Recur(Recur.WEEKLY, Integer.MAX_VALUE);
            recur.getDayList().add(WeekDay.SU);
            RRule rule = new RRule(recur);
            event.getProperties().add(rule);
            // 提醒,提前10分钟
            VAlarm valarm = new VAlarm(new Dur(0, 0, -10, 0));
            valarm.getProperties().add(new Summary("Event Alarm"));
            valarm.getProperties().add(Action.DISPLAY);
            valarm.getProperties().add(new Description("Progress Meeting at 10:30am"));
            // 将VAlarm加入VEvent
            event.getAlarms().add(valarm);
            // 添加事件
            calendar.getComponents().add(event);
            // 验证
            calendar.validate();
            FileOutputStream fout = new FileOutputStream(filePath);
            CalendarOutputter outputter = new CalendarOutputter();

            outputter.output(calendar, fout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
